In this recipe we look into the character codes behind the letters.Discussion
All of the letters and digits you see on a Web page have numerical values called 'character codes.' For example, the letter 'A' has the character code 65, and its lowercase counterpart 'a' has the character code 97 (you can check this above). The ability to move back and forth between these two representations of a letter or digit can be very useful when writing JavaScript. For example, in the Spreadsheet II recipe, compatible with JavaScript 1.1 and lower, it was necessary to write the following bit of code to translate a row designation to a number:var CellID = "~ABCDEFGHIJKLMNOPQRSTUVWXYZ"; . . . //-------------------------------------------------------------------------- // Converts cell alpha reference ([A]1,[B]2,[C]3...) into array index. //-------------------------------------------------------------------------- function toCellIndex(f) { f = f.toUpperCase(); var n=CellID.indexOf(f); if(n == -1) n = 1; return n - 1; }This is bulky and only partially portable. With JavaScript 1.2 it would have been possible to writefunction toCellIndex(cellRef) // cellRef is A1, B3, etc. { return cellRef.charCodeAt(0) - 64; // 1 less than the value of 'A' }The ability to translate numbers to characters is also useful in later recipes, when we write scripts that can handle keyboard input.JavaScript 1.2 can also convert numbers to characters. The String.fromCharCode() function takes any number of numeric arguments, and returns a string which is the concatentation of the characters represented by the arguments. Here's the result of String.fromCharCode(67,65,84):''. (Review the source to this page to make sure we aren't cheating!)
Unless you're using an international version of a browser, there won't be character codes higher than 255 (the range is 0-255). In actual practice, sending it 255 as an argument causes Netscape Communicator to toss up alert dialogs until it crashes your computer--therefore, we don't recommend it.
Copyright ©1998 by Charles River Media, All Rights Reserved